<template>
  <div>
    <el-button
      v-if="canEdit"
      type="primary"
      @click="openDialog"
      style="margin-bottom: 12px"
    >新增催缴/沟通</el-button>
    <el-table :data="reminderList" style="width: 100%">
      <el-table-column prop="reminderType" label="类型" :formatter="formatReminderType" width="80" />
      <el-table-column prop="reminderContent" label="内容" min-width="200">
        <template #default="scope">
          <SmartTooltip>
            <template #content>
              <div>类型: {{ REMINDER_TYPE_MAP[scope.row.reminderType as keyof typeof REMINDER_TYPE_MAP] || '-' }}</div>
              <div>内容: {{ scope.row.reminderContent || '-' }}</div>
              <div>记录时间: {{ formatDateTime(scope.row.reminderTime) }}</div>
              <div>下次到期日: {{ formatDate(scope.row.nextDueDate, 'YYYY-MM-DD') || '-' }}</div>
              <div>下次应缴金额: {{ scope.row.nextAmount ? `¥${scope.row.nextAmount}` : '-' }}</div>
              <div>备注: {{ scope.row.remark || '-' }}</div>
            </template>
            <span class="content-cell">{{ scope.row.reminderContent }}</span>
          </SmartTooltip>
        </template>
      </el-table-column>
      <el-table-column prop="reminderTime" label="记录时间" :formatter="formatReminderTime" width="160" />
      <el-table-column prop="nextDueDate" label="下次到期日" :formatter="formatNextDueDate" width="120" />
      <el-table-column prop="nextAmount" label="下次应缴金额" width="120" />
      <el-table-column prop="remark" label="备注" min-width="150">
        <template #default="scope">
          <SmartTooltip>
            <template #content>
              <div>{{ scope.row.remark || '无备注' }}</div>
            </template>
            <span class="content-cell">{{ scope.row.remark || '-' }}</span>
          </SmartTooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button 
            v-if="canEdit"
            type="primary" 
            @click="editReminder(scope.row)"
          >
            编辑
          </el-button>
          <el-button 
            v-if="canEdit"
            type="success" 
            @click="handleSyncToFee(scope.row)"
            :disabled="!scope.row.nextDueDate && !scope.row.nextAmount"
          >
            生效
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <ReminderRecordDialog
      v-model:visible="dialogVisible"
      :feeId="feeId"
      :feeType="feeType"
      :editData="editData"
      @refresh="fetchReminders"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { REMINDER_TYPE_MAP } from '../constants/enums';
import ReminderRecordDialog from './ReminderRecordDialog.vue';
import { reminderApi } from '@/api/property';
import { formatDateTime, formatDate } from '@/utils';
import SmartTooltip from '@/components/SmartTooltip.vue';
import { showSuccess, showError, showWarning } from '@/utils/message';

const props = defineProps<{ 
  feeId: number; 
  feeType: number; 
  canEdit?: boolean;
}>();
const emit = defineEmits(['sync-success']);
const reminderList = ref<any[]>([]);
const dialogVisible = ref(false);
const editData = ref<any>(null);

function formatReminderType(row: any) {
  return REMINDER_TYPE_MAP[row.reminderType as keyof typeof REMINDER_TYPE_MAP] || '-';
}
function formatReminderTime(row: any) {
  return formatDateTime(row.reminderTime);
}
function formatNextDueDate(row: any) {
  return formatDate(row.nextDueDate, 'YYYY-MM-DD');
}
function openDialog() {
  editData.value = null;
  dialogVisible.value = true;
}
function editReminder(row: any) {
  const recordId = row.id || row.reminderId || row.recordId;
  console.log('【editReminder】row:', row, 'row.id:', row.id, 'row.reminderId:', row.reminderId, 'row.recordId:', row.recordId, '最终使用的id:', recordId);
  // 打印 reminderList，确认 row 是否 reminderList 里的对象
  console.log('【editReminder】当前 reminderList:', reminderList.value);
  editData.value = { ...row, id: recordId };
  // 打印 editData
  console.log('【editReminder】editData.value:', editData.value);
  dialogVisible.value = true;
}

// 生效功能 - 同步催缴记录到主表
async function handleSyncToFee(row: any) {
  try {
    // 检查是否有下次到期日或下次应缴金额
    if (!row.nextDueDate && !row.nextAmount) {
      showWarning('该记录没有下次到期日或下次应缴金额，无法生效');
      return;
    }

    // 构造同步参数
    const syncData = {
      feeId: props.feeId,
      feeType: props.feeType,
      nextDueDate: row.nextDueDate,
      nextAmount: row.nextAmount
    };

    console.log('【handleSyncToFee】同步参数:', syncData);

    // 调用后端接口
    const response = await reminderApi.syncToFee(syncData);
    
    if (response.code === 200) {
      showSuccess('生效成功，催缴记录已同步到主表');
      // 刷新催缴记录列表
      await fetchReminders();
      // 通知父组件生效成功，关闭弹窗并刷新费用列表
      emit('sync-success');
    } else {
      showError(response.message || '生效失败');
    }
  } catch (error: any) {
    console.error('生效失败:', error);
    showError(error.message || '生效失败，请重试');
  }
}

async function fetchReminders() {
  const params = { feeId: props.feeId, feeType: props.feeType };
  const res = await reminderApi.getReminderRecords(params);
  console.log('【fetchReminders】接口原始返回:', JSON.stringify(res.data));
  reminderList.value = res?.data || [];
  console.log('【fetchReminders】最终 reminderList:', JSON.stringify(reminderList.value));
}
onMounted(fetchReminders);

watch(
  () => [props.feeId, props.feeType],
  () => {
    fetchReminders();
  }
);
</script>

<style scoped>
.content-cell {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  cursor: pointer;
}
.content-cell:hover {
  color: #409eff;
}
</style> 